package com.zretc.util;


import com.zretc.service.ChatService;
import com.zretc.service.impl.ChatServiceImpl;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by Administrator on 2020/8/20.
 */
@ServerEndpoint("/chatroom/{sendUser}")
@Component
public class Chatman {
    private static int onLineCount;
    public static ConcurrentHashMap<String,Chatman> chatroom = new ConcurrentHashMap<String,Chatman>();
    private Session session;
    private String sendUser;
    private String receiveUser;
    private String msgContent;

    private ChatService chatService = new ChatServiceImpl();

    public  synchronized void addOnLineCount(){
        Chatman.onLineCount++;
    }

    public  synchronized void subOnLineCount(){

            Chatman.onLineCount--;
    }

    public  synchronized Integer getOnLineCount(){
        return Chatman.onLineCount;
    }

    public void sendMessage(String type,String msg){
        System.out.println("sendmessage11111");
        System.out.println(msg);
        if(type.equals("count")){
            try {
                this.session.getBasicRemote().sendText("count:"+msg);
                System.out.println("sendmessage22222");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            try {
                this.session.getBasicRemote().sendText(msg);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @OnOpen
    public void onOpen(@PathParam("sendUser")String sendUser,Session session){
        System.out.println("open=====");
        System.out.println(sendUser);
        Chatman user = this;
        this.sendUser = sendUser;
        this.session = session;
        addOnLineCount();
        chatroom.put(sendUser,user);
        this.chatService.getChatmanAndInit(this.sendUser);
        for (Chatman cm:chatroom.values()) {
           cm.sendMessage("count",getOnLineCount()+"");
        }
    }
    @OnClose
    public void onClose(@PathParam("sendUser")String sendUser,Session session){
        System.out.println("close=====");
        this.sendUser = sendUser;
        this.session = session;
        subOnLineCount();
        for (Chatman cm:chatroom.values()) {
            if(cm.session!=this.session){
                cm.sendMessage("count",getOnLineCount()+"");
            }
        }
    }
    @OnMessage
    public void onMessage(String jsonMsg, Session session) throws IOException {
        System.out.println("onmessage");
        JSONObject jsonOject = JSONObject.fromObject(jsonMsg);
        sendUser = jsonOject.getString("sendUser");
        receiveUser = jsonOject.getString("toUser");
        msgContent = jsonOject.getString("message");
        msgContent =  receiveUser +"," + msgContent + " \r\n";
        // 得到接收人
        Chatman user = chatroom.get(receiveUser);
        if (user == null) {//如果接收人不存在则保持到数据库
            System.out.println("信息已保存到数据库");
            chatService.sendAndSaveMsessage(sendUser, receiveUser,msgContent);
            chatService.getAndReceiveMsessage(receiveUser);
            return;
        }
        //接收websocet发送的消息，存到生产者里,然后实例化消费者对象
        chatService.sendAndSaveMsessage(sendUser, receiveUser,msgContent);
        chatService.getAndReceiveMsessage(receiveUser);
    }

    @OnError
    public void onError(Session session,Throwable error){
        System.out.println("error");
        error.printStackTrace();
    }
}
